package com.trw.trp.action;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.mail.SendFailedException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ApplicationAware;

import com.trw.trp.bean.MailBean;
import com.trw.trp.bean.ModelBean;
import com.trw.trp.bean.ModelDetail;
import com.trw.trp.bean.OrderBean;
import com.trw.trp.dao.DaoFactory;
import com.trw.trp.dao.MailDao;
import com.trw.trp.util.TRPConstants;
import com.trw.trp.util.TRPUtil;
import com.utuan.log.Log;
import com.utuan.log.LogFactory;

public class AbstractAction implements ApplicationAware {
	
	private static Log log = LogFactory.getLog(AbstractAction.class);
			
	private Map<String, Object> application;

	protected static String MODEL_IDX = "modelIdx";
	protected static String CURRENT_MODEL = "currentModelDetail";

	// return result
	protected static String SUCCESS = "success";
	protected static String COMPLETE = "complete";
	protected static String SKIP_MATRIX = "skipMatrix";

	protected static String VALUE_SEPARATOR = "|x|";

	protected String trimValue(String value) {
		value = StringUtils.trimToEmpty(value);
		if (TRPConstants.NULL_STRING.equalsIgnoreCase(value)) {
			value = TRPConstants.EMPTY_STRING;
		}
		return value;
	}

	protected void writeJSON(Object obj) throws IOException {
		JSONObject json = JSONObject.fromObject(obj);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.getWriter().write(json == null ? "" : json.toString());
	}

	protected void writeJSON4Form(boolean success, Object obj)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("success", success);
		map.put("data", obj);
		JSONObject json = JSONObject.fromObject(map);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.getWriter().write(json.toString());
	}

	protected void writeJSON(List<?> beanList) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("size", beanList == null ? 0 : beanList.size());
		map.put("items", beanList);
		JSONObject jsonObject = JSONObject.fromObject(map);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.getWriter().write(jsonObject.toString());
	}

	protected void writeJSON(List<?> beanList, int start, int limit)
			throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("size", beanList == null ? 0 : beanList.size());
		map.put("items",
				beanList == null ? Collections.EMPTY_LIST : beanList.subList(
						start, Math.min(start + limit, beanList.size())));
		JSONObject jsonObject = JSONObject.fromObject(map);
		HttpServletResponse response = ServletActionContext.getResponse();
		response.getWriter().write(jsonObject.toString());
	}

	protected void setToRequest(String key, Object value) {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request != null) {
			request.setAttribute(key, value);
		}
	}

	protected String getParamFromRequest(String key) {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request != null) {
			return request.getParameter(key);
		}
		return null;
	}

	protected Object getAttributeFromRequest(String key) {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request != null) {
			return request.getAttribute(key);
		}
		return null;
	}

	protected String[] getParamsFromRequest(String key) {
		HttpServletRequest request = ServletActionContext.getRequest();
		if (request != null) {
			return request.getParameterValues(key);
		}
		return null;
	}

	public void setApplication(Map<String, Object> application) {
		this.application = application;
	}

	protected Map<String, Object> getApplication() {
		return this.application;
	}

	protected ModelDetail getModelDetail(int idx) {
		ModelDetail detail = null;
		OrderBean order = (OrderBean) TRPUtil
				.getFromSession(TRPConstants.CURRENT_ORDER);
		Integer modelStatus = (Integer) TRPUtil
				.getFromSession(TRPConstants.CURRENT_MODEL_STATUS);

		if (order.getDetailMap() != null) {
			List<ModelDetail> modelDetails = order.getDetailMap().get(
					modelStatus);
			if (modelDetails != null && !modelDetails.isEmpty()) {
				detail = modelDetails.get(idx);
			}
		}
		return detail;
	}

	protected ModelBean getModel(int idx) {
		ModelBean model = null;
		OrderBean order = (OrderBean) TRPUtil
				.getFromSession(TRPConstants.CURRENT_ORDER);
		Integer modelStatus = (Integer) TRPUtil
				.getFromSession(TRPConstants.CURRENT_MODEL_STATUS);

		if (order.getModelMap() != null) {
			List<ModelBean> models = order.getModelMap().get(modelStatus);
			if (models != null && !models.isEmpty()) {
				model = models.get(idx);
			}
		}
		return model;
	}
	
	protected String generateEmail(Object[] params) {
		String result = null;
		try {
			String subject = null;
			String body = null;
			String toUser = getParamFromRequest("to");
			String ccUser = getParamFromRequest("cc");
			String emailIdStr = getParamFromRequest("emailId");
			long mailId = -1;
			try {
				mailId = Long.parseLong(emailIdStr);
			} catch (Exception e) {
				log.warn(e);
			}
			MailDao dao = DaoFactory.getMailDao();
			MailBean mailBean = dao.getMail(mailId);

			if (mailBean != null) {
				subject = mailBean.getSubject();
				body = mailBean.getBody();
				if (params != null && params.length > 0) {
					body = MessageFormat.format(body, params);
				}
			}
			TRPUtil.sendMail(toUser, ccUser, subject, body);
			result = new StringBuilder()
					.append("Email has been successfully sent out to:")
					.append(toUser).append(TRPConstants.COMMA).append(ccUser)
					.toString();
		} catch (SendFailedException e) {
			log.warn(e);
			result = new StringBuilder()
					.append("Email send failed due to invalid address:")
					.append(Arrays.toString(e.getInvalidAddresses()))
					.toString();
		} catch (Exception e) {
			log.warn(e);
			result = e.getMessage();
		}
		return result;
	}

}
